﻿using System;
using System.Diagnostics;
using Threads;

namespace AutoBuildVersion.Helper
{
    public class CmdRuner
    {
        /// <summary>
        /// cmd进程变量
        /// </summary>
        private Process CmdProcess = new Process();

        public CmdRuner(string cmd)
        {
            Cmd = cmd;
        }

        /// <summary>
        ///     命令文本
        /// </summary>
        private string Cmd { set; get; }

        public void RunCmd(Action<DataReceivedEventArgs> outputAction, Action<DataReceivedEventArgs> errAction, Action<EventArgs> exitedAction)
        {
            CmdProcess.StartInfo.FileName = "CMD.EXE"; // 命令  


            CmdProcess.StartInfo.CreateNoWindow = true; // 不创建新窗口  
            CmdProcess.StartInfo.UseShellExecute = false;
            CmdProcess.StartInfo.RedirectStandardInput = true; // 重定向输入  
            CmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向标准输出  
            CmdProcess.StartInfo.RedirectStandardError = true; // 重定向错误输出  
           
            CmdProcess.OutputDataReceived += ((sender, e) =>
            {
                if (outputAction != null)
                    outputAction(e);
            });


            CmdProcess.ErrorDataReceived += ((sender, e) =>
            {
                if (errAction != null)
                    errAction(e);
            });

            CmdProcess.EnableRaisingEvents = true; // 启用Exited事件  
            CmdProcess.Exited += ((sender, e) =>
            {
                if (exitedAction != null)
                    exitedAction(e);
            }); ; // 注册进程结束事件  

            CmdProcess.Start();




            CmdProcess.StandardInput.WriteLine(Cmd); // Cmd 命令
            CmdProcess.StandardInput.WriteLine("exit"); // 退出
            CmdProcess.BeginOutputReadLine();
            CmdProcess.BeginErrorReadLine();

            // 如果打开注释，则以同步方式执行命令，此例子中用Exited事件异步执行。  
            // CmdProcess.WaitForExit();       
        }

    }
}